package com.ruoyi.partybuilding.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.easy.query.core.api.pagination.EasyPageResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.partybuilding.common.EQuery.IDeptEntity;
import com.ruoyi.partybuilding.common.EQueryHelper;
import com.ruoyi.partybuilding.common.PageSort;
import com.ruoyi.partybuilding.domain.*;
import com.ruoyi.partybuilding.domain.vo.DeptOrgVo;
import com.ruoyi.partybuilding.domain.vo.ScoreTypeVo;
import com.ruoyi.partybuilding.domain.vo.ScoreYearStatVo;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.partybuilding.mapper.WorkScoreMapper;
import com.ruoyi.partybuilding.service.IWorkScoreService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;

/**
 * 个人积分Service业务层处理
 * 
 * @author he-liangliang@outlook.com
 * @date 2024-11-27
 */
@Service
public class WorkScoreServiceImpl implements IWorkScoreService 
{
    @Autowired
    private WorkScoreMapper workScoreMapper;

    @Resource
    protected EQueryHelper queryHelper;

    @Resource
    OrgServiceImpl orgService;

    final  static String itemSql="select * from pb_score_type st left join( SELECT sum(add_score) year_sum,max(title) title,title_id,year_sign,user_id,max(user_name) user_name,max(dept_id) dept_id,max(org_name) org_name from pb_work_score WHERE approval_status=10000 %s GROUP BY title_id,year_sign,user_id) ws on st.id=ws.title_id where type=0 ";
    final  static String orgItemSql="select * from pb_score_type st left join( SELECT sum(add_score) year_sum,max(title) title,title_id,year_sign,max(user_id) user_id,max(user_name) user_name,dept_id,max(org_name) org_name from pb_work_score WHERE approval_status=10000 %s GROUP BY title_id,year_sign,dept_id) ws on st.id=ws.title_id where st.type=1 ";
    public R<List<ScoreTypeVo>> memberItemStat(Long year,Long userId){
        var nowSql=String.format(itemSql," and year_sign="+year+" and user_id="+userId);
       var list= queryHelper.CreateItems(nowSql).addItem(" order by st.sort").resultPkg().sqlQuery(ScoreTypeVo.class);
       return R.ok(list);
    }

    public R<List<ScoreTypeVo>> orgItemStat(Long year,Long deptId){

        var nowSql=String.format(orgItemSql," and year_sign="+year+" and dept_id="+deptId);
        var list= queryHelper.CreateItems(nowSql).addItem(" order by st.sort").resultPkg().sqlQuery(ScoreTypeVo.class);
        return R.ok(list);
    }

    /** 组织年积分统计
     *
     * @param whereObj
     * @param page
     * @return
     */
    public EasyPageResult<ScoreYearStatVo> orgYearStat(ScoreYearStatVo whereObj, PageSort page) {
        var wsq = queryHelper.queryable(WorkScore.class).where(p -> p.eq(WorkScore::getApprovalStatus, WorkScore.ApprovalPassEnd).eq(WorkScore::getType, 1));
        var re2 = queryHelper.queryable(SysDeptRef.class)
                .leftJoin(wsq, (p1, p2) -> p1.eq(p2, SysDeptRef::getDeptId, WorkScore::getDeptId))
                .where((p1, p2) -> p1.eq(SysDeptRef::getDelFlag, 0)) //eq(WorkScore::getApprovalStatus, 10000)
                .groupByMerge(p -> p.t().column(SysDeptRef::getDeptId))
                .groupByMerge(p -> p.t1().column(WorkScore::getYearSign))
                .select(ScoreYearStatVo.class, (p, p2) -> {
                    p.column(SysDeptRef::getDeptId);
                    p.columnMax(SysDeptRef::getDeptName);
                    p2.columnSumAs(WorkScore::getAddScore, ScoreYearStatVo::getScoreSum);
                    p2.column(WorkScore::getYearSign);
                })
                .whereObject(whereObj)
                .where(whereObj.getYearSign() != null, p -> {
                    p.and(()->{
                        p.eq(ScoreYearStatVo::getYearSign, whereObj.getYearSign()).or().isNull(ScoreYearStatVo::getYearSign);
                    });
                })
                .orderByObject(StringUtils.isNotBlank(page.getOrderByName()), page)
                .toPageResult(page.getPageNum(), page.getPageSize());
        return re2;
    }

    /**
     *  党员年积分统计，如果传deptId则查询此部门及其子部门
     * @param whereObj 如果传deptId则查询此部门及其子部门
     * @param page
     * @return
     */
    public EasyPageResult<ScoreYearStatVo> memberYearStat(ScoreYearStatVo whereObj, PageSort page) {
        var deptId = whereObj.getDeptId();
        List<Long> deptIds = deptId == null ? null : orgService.queryAndSubs(deptId).getData().stream().map(DeptOrgVo::getDeptId).collect(Collectors.toList());
        whereObj.setDeptId(null);
        var wsq = queryHelper.queryable(WorkScore.class).where(p -> p.eq(WorkScore::getApprovalStatus, WorkScore.ApprovalPassEnd).eq(WorkScore::getType, 0));
        var re = queryHelper.queryable(Member.class)
                .leftJoin(SysUserRef.class, (p, p2) -> p.eq(p2, Member::getUserId, SysUserRef::getUserId))
                .leftJoin(wsq, (p1, p2, p3) -> p1.eq(p3, Member::getUserId, WorkScore::getUserId))
                .where((p1, p2, p3) -> p2.isNotNull(SysUserRef::getUserId)) //eq(WorkScore::getApprovalStatus, 10000)
                .groupByMerge(p -> p.t().column(Member::getUserId))
                .groupByMerge(p -> p.t2().column(WorkScore::getYearSign))
                .select(ScoreYearStatVo.class, (p, p2, p3) -> {
                    p.column(Member::getUserId);
                    p2.columnMax(SysUserRef::getDeptId);
                    p2.columnMax(SysUserRef::getNickName);
                    p3.columnSumAs(WorkScore::getAddScore, ScoreYearStatVo::getScoreSum);
                    p3.column(WorkScore::getYearSign);
                    p3.columnMaxAs(WorkScore::getOrgName, ScoreYearStatVo::getDeptName);
                })
                .whereObject(whereObj)
                .where(whereObj.getYearSign() != null, p -> {
                    p.and(() -> {
                        p.eq(ScoreYearStatVo::getYearSign, whereObj.getYearSign()).or().isNull(ScoreYearStatVo::getYearSign);
                    });
                })
                .where(deptIds != null, p -> p.in(ScoreYearStatVo::getDeptId, deptIds))
                .orderByObject(StringUtils.isNotBlank(page.getOrderByName()), page)
                .toPageResult(page.getPageNum(), page.getPageSize());
        var orgList = orgService.deptVoList(null);
        re.getData().forEach(p -> {
            if (StringUtils.isBlank(p.getDeptName())) {
                var tmp = orgList.getData().stream().filter(x -> Objects.equals(x.getDeptId(), p.getDeptId())).findFirst();
                tmp.ifPresent(z -> p.setDeptName(z.getDeptName()));
            }
        });
        return re;
    }

    @Resource
    MallPointsServiceImpl mallPointsService;

    @Transactional
    public R approve(Boolean isPass,String remark,List<Long> dtoIds,String approveUserName) {
        var ids = dtoIds.stream().distinct().collect(Collectors.toList());
        var olds = queryHelper.queryable(WorkScore.class).where(p -> p.in(WorkScore::getId, ids)).toList();
        if (olds.size() < 1)
            return R.bad("审批实体无法找到");
        var unifyStatus = isPass ? 1 : -1;
        var type = olds.get(0).getType();
        var list = new ArrayList<MallPoints>();
        for (var item : olds) {
            if (!type.equals(item.getType()))
                return R.fail("积分类型不统一");
            item.approveSet(unifyStatus, remark, approveUserName);
            //
            if (unifyStatus == 1) {
                var points = mallPointsService.newPoints(item.getUserId(), item.getAddScore().doubleValue(), "workSorce:" + item.getId(), "积分申请");
                list.add(points);
            }
        }
        queryHelper.query().updatable(olds).executeRows();
        if (unifyStatus == 1)
            queryHelper.query().insertable(list).executeRows();
        return R.ok();
    }
    /**
     * 查询个人积分
     * 
     * @param id 个人积分主键
     * @return 个人积分
     */
    @Override
    public WorkScore selectWorkScoreById(Long id)
    {
        return workScoreMapper.selectWorkScoreById(id);
    }

    /**
     * 查询个人积分列表
     * 
     * @param workScore 个人积分
     * @return 个人积分
     */
    @Override
    public List<WorkScore> selectWorkScoreList(WorkScore workScore)
    {
        return workScoreMapper.selectWorkScoreList(workScore);
    }

    /**
     * 新增个人积分
     * 
     * @param workScore 个人积分
     * @return 结果
     */
    @Override
    public int insertWorkScore(WorkScore workScore)
    {
        workScore.setCreateTime(DateUtils.getNowDate());
        return workScoreMapper.insertWorkScore(workScore);
    }

    /**
     * 修改个人积分
     * 
     * @param workScore 个人积分
     * @return 结果
     */
    @Override
    public int updateWorkScore(WorkScore workScore)
    {
        return workScoreMapper.updateWorkScore(workScore);
    }

    /**
     * 批量删除个人积分
     * 
     * @param ids 需要删除的个人积分主键
     * @return 结果
     */
    @Override
    public int deleteWorkScoreByIds(Long[] ids)
    {
        return workScoreMapper.deleteWorkScoreByIds(ids);
    }

    /**
     * 删除个人积分信息
     * 
     * @param id 个人积分主键
     * @return 结果
     */
    @Override
    public int deleteWorkScoreById(Long id)
    {
        return workScoreMapper.deleteWorkScoreById(id);
    }
}
